package de.sp.games.snake12k.boxes;

import java.util.Random;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;

import de.sp.games.snake12k.Field;
import de.sp.games.snake12k.SUtil;

public class PickUpBox extends Box implements IBoxable {
	private Random random = new Random();
	private Field field;
	private SnakeBox snake;
	public boolean removed = false;
	private boolean bigBodyRendered = false;
	private int startValue = 0;
	private int snakeLength = 0;

	Sound picup = new Sound("ressource/pic_up.wav");

	public PickUpBox(int x, int y, final int indexX, final int indexY, SnakeBox snake, Field field) throws SlickException {
		super(x, y, new Image("ressource/box_empty.jpg"), indexX, indexY);
		this.field = field;
		this.snake = snake;
		int rand = random.nextInt(3);
		Image image = new Image("ressource/pickup_tiles.png");
		image.setFilter(Image.FILTER_NEAREST);

		if (rand == 0) {
			image = image.getSubImage(0, 0, 16, 16);
		} else if (rand == 1) {
			image = image.getSubImage(16, 16, 16, 16);
		} else if (rand == 2) {
			image = image.getSubImage(32, 32, 16, 16);
		}

		isCollision = false;
		isChangeable = true;
		boxImage = image;
	}

	public void update() throws SlickException {
		isEaten();

		if (SUtil.isTimeMove()) {
			if (startValue >= this.snakeLength + 2) {
				bigBodyRendered = false;
				field.picUpList.remove(this);
			} else if (bigBodyRendered) {
				startValue++;
			}
		}
	}

	public void draw(Graphics g) {
		if (!removed) {
			super.draw(g);
		}
		if (bigBodyRendered) {
			//Image is 2px bigger
			boxImage.draw(x - 1, y - 1);
		}
	}

	private void isEaten() throws SlickException {
		if (!removed) {
			if (snake.getIndexX() == this.getIndexX() && snake.getIndexY() == this.getIndexY()) {

				picup.play();
				SUtil.addSnakeLength();
				bigBodyRendered = true;
				this.snakeLength = SUtil.snakeLength;
				boxImage = new Image("ressource/big_body.jpg");
				boxImage.setFilter(Image.FILTER_NEAREST);

				removed = true;
				field.createPickUpRandom();
			}
		}
	}
}
